package cn.tedu.api;

import java.math.BigDecimal;
import java.util.Scanner;

/**本类用于解决浮点数运算不精确的问题*/
public class TestBigDecimal {
    public static void main(String[] args) {
//        f1();
        f2();
    }
    private static void f2(){
        System.out.println("请您输入您要计算的两个数");
        Scanner scanner = new Scanner(System.in);
        double a = scanner.nextDouble();
        double b = scanner.nextDouble();
        BigDecimal bd1 = new BigDecimal(a+"");
        BigDecimal bd2 = new BigDecimal(b+"");

        BigDecimal bd3;

        bd3 = bd1.add(bd2);
        System.out.println("加法:"+bd3);

        bd3 = bd1.subtract(bd2);
        System.out.println("减法:"+bd3);

        bd3 = bd1.multiply(bd2);
        System.out.println("乘法:"+bd3);

        /*除法运算,除不尽时会抛出异常
         * 注意使用重载的除法方法:divide(x,y,z)
         * x:要除以哪个对象 y指的是保留位数 z:指的是舍入方式(四舍五入)*/
        //bd3 = bd1.divide(bd2);//除法运算
        bd3 = bd1.divide(bd2,3,BigDecimal.ROUND_HALF_UP);
        System.out.println("除法:"+bd3);

    }
    private static void f1(){
        System.out.println("请您输入您要计算的两个数");
        Scanner scanner = new Scanner(System.in);
        double a = scanner.nextDouble();
        double b = scanner.nextDouble();

        //使用接收到的两个小数直接做普通的四则运算--不精确
        System.out.println(a+b);
        System.out.println(a-b);
        System.out.println(a*b);
        System.out.println(a/b);

    }
}
